﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using System.Windows;
using System.Threading;
using System.ComponentModel.Design;
using System.Diagnostics;

namespace BugTracker
{
    static class DBWork
    {
        private static OdbcConnection m_DBCon = new OdbcConnection();
        private static String m_errorStr = "";
        private static int m_errorCode = 0;
        private static object locker = new object();
        private static Thread MessageThread = null;
        private static EventWaitHandle MessageEvent = new ManualResetEvent(true);   //Изначально свободен, чтобы поток завершился

        public static String DSN;

        public static bool Connect(String UserName, String Password)
        {
            m_errorStr = "";
            m_errorCode = 0;
            if (Active)
                return true;

            // Подключение источника
            try
            {
                m_DBCon.ConnectionString = "DSN=" + DSN;
                m_DBCon.Open();
            } catch (OdbcException ex)
            {
                m_errorStr = ex.Message;
                m_errorCode = ex.ErrorCode;
                return false;
            };

            // Проверка Логина/пароля
            DBWDataSet DBSet = ExecuteSQL("call LOGIN('LOGIN=\"" + UserName +  "\";PWD=\"" + Password + "\";')");
            DBSet.Read();
            if (DBSet.ErrorSet())
            {
                m_errorStr = DBSet.GetString("ERROR_MSG");
                m_errorCode = DBSet.GetInt32("ERROR_CODE");
                m_DBCon.Close();
                return false;
            };
            DBSet.Dispose();

            // Стартую поток с сообщениями
            if (MessageThread == null)
            {
                MessageThread = new Thread(MessageThreadBody);
                MessageThread.Name = "MessageThread";
                MessageThread.IsBackground = true;
                MessageThread.Priority = ThreadPriority.Lowest;
                MessageEvent.Reset();
                MessageThread.Start();
            };

            return true;
        }
        public static void Disconnect()
        {
            if (Active)
                m_DBCon.Close();
            m_errorStr = "";
            m_errorCode = 0;
            // Торможу поток с сообщениями
            if (MessageThread != null)
            {
                MessageEvent.Set();
                MessageThread.Join();
                MessageThread = null;
            };
        }

        public static DBWDataSet ExecuteSQL(String SQLCommand)
        {
            DBWDataSet ret = null;
            lock (locker)
            {
                Trace.Write(SQLCommand + '\n');
                m_errorStr = "";
                m_errorCode = 0;
                if (!Active)
                {
                    m_errorStr = "Not connected to DB";
                    m_errorCode = -1;
                    return ret;
                };
                ret = new DBWDataSet(m_DBCon, SQLCommand);
            };
            return ret;
        }

        public static bool Active
        {
            get
            {
                return (m_DBCon.State == System.Data.ConnectionState.Open);
            }
        }
        public static String ErrorStr
        {
            get
            {
                return m_errorStr;
            }
        }
        public static int ErrorCode
        {
            get
            {
                return m_errorCode;
            }
        }

        private static void MessageThreadBody()
        {
            Trace.Write("Thread Started!\n");
            try
            {
                while (!MessageEvent.WaitOne(TimeSpan.FromSeconds(constants.MessageThreadSleepTime)))
                {
                    // Проверка наличия сообщений
                    DBWDataSet DBSet = ExecuteSQL("call MESSAGES_GET_COUNT()");
                    DBSet.Read();
                    if (DBSet.FieldExists("MSG_COUNT"))
                        if (DBSet.GetInt32("MSG_COUNT") > 0)
                        {
                            // Тут что нибудь, заставляющее главное окно обновиться
                        };
                    DBSet.Dispose();
                };
            } catch (Exception)
            {

            };
            Trace.Write("Thread Died!\n");
        }
    }
}
